package org.jeecg.modules.demo.crm.service.impl;

import org.jeecg.common.util.CommonUtils;
import org.jeecg.modules.demo.crm.entity.CQuotation;
import org.jeecg.modules.demo.crm.entity.CQuotationInfo;
import org.jeecg.modules.demo.crm.entity.CQuotationMail;
import org.jeecg.modules.demo.crm.entity.CQuotationMaterials;
import org.jeecg.modules.demo.crm.mapper.CQuotationInfoMapper;
import org.jeecg.modules.demo.crm.mapper.CQuotationMapper;
import org.jeecg.modules.demo.crm.mapper.CQuotationMaterialsMapper;
import org.jeecg.modules.demo.crm.service.ICQuotationMaterialsService;
import org.jeecg.modules.demo.crm.service.ICQuotationService;
import org.jeecg.modules.demo.crm.util.execl.AsposeCellsUtil;
import org.jeecg.modules.demo.crm.util.wx.WxAvatar2MultipartFile;
import org.jeecg.modules.demo.task.ExcelReportGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static org.jeecg.modules.demo.crm.util.execl.ExcelReportGeneratorUtils.downloadTemplate;
import static org.jeecg.modules.demo.crm.util.execl.ExcelReportGeneratorUtils.generateExcel;

/**
 * @Description: 工程报价单
 * @Author: jeecg-boot
 * @Date:   2025-08-28
 * @Version: V1.0
 */
@Service
public class CQuotationServiceImpl extends ServiceImpl<CQuotationMapper, CQuotation> implements ICQuotationService {

    @Autowired
    private CQuotationMapper cQuotationMapper;

    @Autowired
    private CQuotationInfoMapper cQuotationInfoMapper;



    @Autowired
    private ICQuotationMaterialsService quotationMaterialsService;

    @Value("${netease.mail.username}")
    private String neteaseFrom;

    @Override
    @Transactional
    public void add(CQuotation cQuotation) {
        cQuotationMapper.insert(cQuotation);
        List<CQuotationMaterials> list = cQuotation.getDetails().stream().map(detail->{
            CQuotationInfo info = CQuotationInfo.builder()
                    .quotationId(cQuotation.getId())
                    .name(detail.getName())
                    .mainMaterial(detail.getMainMaterial())
                    .auxMaterial(detail.getAuxMaterial())
                    .quantity(detail.getQuantity())
                    .unit(detail.getUnit())
                    .labor(detail.getLabor())
                    .total(detail.getTotal())
                    .remarks(detail.getRemarks())
                    .build();
            cQuotationInfoMapper.insert(info);
            if (cQuotation.getIsStorage()){
                CQuotationMaterials vo = CQuotationMaterials.builder()
                        .projectName(cQuotation.getName())
                        .projectNumber(cQuotation.getProjectNumber())
                        .contractNumber(cQuotation.getProjectNumber())
                        .libraryId(cQuotation.getLibraryId())
                        .quotationId(cQuotation.getId())
                        .name(detail.getName())
                        .mainMaterial(detail.getMainMaterial())
                        .auxMaterial(detail.getAuxMaterial())
                        .quantity(detail.getQuantity())
                        .unit(detail.getUnit())
                        .labor(detail.getLabor())
                        .total(detail.getTotal())
                        .remarks(detail.getRemarks())
                        .source("工程报价记录")
                        .build();
                return vo;
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        if (list.size() > 0){
            quotationMaterialsService.saveBatch(list);
        }
    }

    @Override
    @Transactional
    public void edit(CQuotation cQuotation) {
        cQuotationMapper.updateById(cQuotation);
        cQuotationInfoMapper.deleteByQuotation(cQuotation.getId());


        List<CQuotationMaterials> list = cQuotation.getDetails().stream().map(detail->{
            CQuotationInfo info = CQuotationInfo.builder()
                    .quotationId(cQuotation.getId())
                    .name(detail.getName())
                    .mainMaterial(detail.getMainMaterial())
                    .auxMaterial(detail.getAuxMaterial())
                    .quantity(detail.getQuantity())
                    .unit(detail.getUnit())
                    .labor(detail.getLabor())
                    .total(detail.getTotal())
                    .remarks(detail.getRemarks())
                    .build();
            cQuotationInfoMapper.insert(info);
            if (cQuotation.getIsStorage()){
                CQuotationMaterials vo = CQuotationMaterials.builder()
                        .projectName(cQuotation.getName())
                        .projectNumber(cQuotation.getProjectNumber())
                        .contractNumber(cQuotation.getProjectNumber())
                        .libraryId(cQuotation.getLibraryId())
                        .quotationId(cQuotation.getId())
                        .name(detail.getName())
                        .mainMaterial(detail.getMainMaterial())
                        .auxMaterial(detail.getAuxMaterial())
                        .quantity(detail.getQuantity())
                        .unit(detail.getUnit())
                        .labor(detail.getLabor())
                        .total(detail.getTotal())
                        .remarks(detail.getRemarks())
                        .source("工程报价记录")
                        .build();
                return vo;
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        if (list.size() > 0){
            quotationMaterialsService.saveBatch(list);
        }

    }

    @Override
    public void delete(String id) {
        cQuotationInfoMapper.deleteByQuotation(id);
        cQuotationMapper.deleteById(id);
    }

    @Override
    public CQuotationMail generateQuotation(String id) {
        CQuotationMail cQuotationMail = new CQuotationMail();
        CQuotation cQuotation = cQuotationMapper.selectById(id);
       /* if(1==1){
            cQuotationMail.setQuotationId(cQuotation.getId());
            cQuotationMail.setSendMaill(neteaseFrom);
            cQuotationMail.setAttachmentUrl("http://154.201.66.67:9000/blithe-crm/temp/quotation/工程报价单_川沙项目备注_S888888888888_20250901143438_1756708482557.xlsx");
            return cQuotationMail;
        }*/
        List<CQuotationInfo> quotationInfoList = new ArrayList<>();
        if(cQuotation != null){
           quotationInfoList = cQuotationInfoMapper.details(id);
        }
        try {
            // 1. 下载模板
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String timestamp = sdf.format(new Date());
            String projectRoot = System.getProperty("user.dir");
            String outputPath = projectRoot + "/execl_工程报价单_"+cQuotation.getName()+"_"+cQuotation.getProjectNumber()+"_ "+ timestamp +".xlsx";
            String outputPdfPath = projectRoot + "/pdf_工程报价单_"+cQuotation.getName()+"_"+cQuotation.getProjectNumber()+"_ "+ timestamp +".pdf";
            File template = downloadTemplate("http://154.201.66.67:9000/blithe-crm/temp/20250912/发送邮件模板_1757656777440.xlsx", "template.xlsx");
            generateExcel(template, outputPath,
                    cQuotation.getName(),
                    cQuotation.getProjectNumber(),
                    cQuotation.getRemark(),
                    cQuotation.getPartyA(),
                    cQuotation.getPartyADate(),
                    cQuotation.getPartyB(),
                    cQuotation.getPartyBDate(),
                    quotationInfoList);
            // 获取项目根目录
            MultipartFile multipartExcelFile = WxAvatar2MultipartFile.convertLocal(outputPath);
            String excelFile = CommonUtils.upload(multipartExcelFile, "temp/quotation", "minio");
            System.out.println("Excel 生成完成：" + excelFile);


            AsposeCellsUtil.excelToPdf(outputPath, outputPdfPath);
            MultipartFile multipartPdfFile = WxAvatar2MultipartFile.convertLocal(outputPdfPath);
            String pdfFile = CommonUtils.upload(multipartPdfFile, "temp/excel", "minio");
            System.out.println("pdf 生成完成：" + pdfFile);

            String base64Images = AsposeCellsUtil.convertFirstPageToBase64(outputPdfPath);

            //String content = cQuotationMail.getContent();
            String contentHtml ="<p><h1></h1></p>" +
                    "<p>"+base64Images+"</p>" +
                    "<hr>";


            //删除本地文件
            Files.delete(Paths.get(outputPath));
            Files.delete(Paths.get(outputPdfPath));

            cQuotationMail.setQuotationId(cQuotation.getId());
            cQuotationMail.setSubject(cQuotation.getName()+"-"+cQuotation.getProjectNumber());
            cQuotationMail.setContent(contentHtml);
            cQuotationMail.setSendMaill(neteaseFrom);
            cQuotationMail.setAttachmentUrl(excelFile+","+pdfFile);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return cQuotationMail;
    }
}
